# -*- coding: utf-8 -*-

import pages.oauth as oauth
from pages.basePage import BaseHandler
import jinja2
import os
from models.usuario import Usuario
from models.cenario import Cenario
from models.persona import Persona

from google.appengine.ext import db
from google.appengine.api import images

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

CONSUMER_KEY='RHIGaaaShak3AS5lAeasiI0VQipvwpD1GShY9j6S'
CONSUMER_SECRET='uYPvneXR4tDHLeJlE91jPRKiD5A4sFVaKeCU37If'
CALLBACL_URL="http://localhost:3000/redu"
REDU_CONSUMER = oauth.get_oauth_client(oauth.REDU, CONSUMER_KEY, CONSUMER_SECRET, CALLBACL_URL)
        
class Redu(BaseHandler):
    def get(self):            
        userId = self.session.get('userid')
        user = Usuario.get_by_id(userId)
        if user is None:
            self.redirect('/')
        
        code = self.request.get('code')
        
        data = dict(code=code,
                    grant_type='authorization_code',
                    redirect_uri='http://localhost:3000/redu')
        
        response = REDU_CONSUMER.get_access_token('POST', data=data)

        self.session['access_token'] = response.content['access_token']    
        self.redirect('/home')

class CenarioCoisado():
    nome = None
    descricao = None
    cid = None
    pid = None

class Home(BaseHandler):
    def get(self):
        userId = self.session.get('userid')        
        user = None
        if userId is not None:
            user = Usuario.get_by_id(userId)
        if user is None:
            self.redirect('/')
            return
        
        url_request_pin = REDU_CONSUMER.get_authorization_url();
        self.session['url'] = url_request_pin
        
        cenarios = Cenario.gql('WHERE usuarioCriador = :1', user.key());
        if cenarios is None:
            cenarios = []
            
        cenariosCoisados = []
        for cenario in cenarios:
            cenarioCoisado = CenarioCoisado()
            cenarioCoisado.nome = cenario.nome
            cenarioCoisado.descricao = cenario.descricao
            cenarioCoisado.cid = cenario.key().id()
            persona = None
            if cenario.persona:
                persona = Persona.get(cenario.persona.key())
            if persona:
                cenarioCoisado.pid = persona.key().id()
            cenariosCoisados.append(cenarioCoisado)
            
        template_values = {
            'user' : user,
            'cenarios' : cenariosCoisados,
            'url' : url_request_pin
        }
            
        template = jinja_environment.get_template('html/projetos.html')
        self.response.out.write(template.render(template_values))
        
    def post(self):
        userId = self.session.get('userid')        
        user = None
        if userId is not None:
            user = Usuario.get_by_id(userId)
        if user is None:
            self.redirect('/')
            return
        
        imagem = images.resize(self.request.get("img"), 200, 100)
        persona = Persona()
        persona.imagem = db.Blob(imagem)
        persona.put()
        self.redirect('/persona?pid=' + str(persona.key().id()))